package com.flycent.hqhs.ui;



import java.lang.ref.WeakReference;
import java.util.List;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flycent.hqhs.App;
import com.flycent.hqhs.R;
import com.flycent.hqhs.bean.CouponCode;
import com.flycent.hqhs.bean.PageEntity;
import com.flycent.hqhs.http.WebClient;
import com.flycent.hqhs.http.WebException;
import com.flycent.hqhs.ui.view.AbsViewHolderAdapter;
import com.flycent.hqhs.ui.view.BadgeView;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy.OnLoadDataActionListener;
import com.flycent.hqhs.util.DateTimeUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

/**
 *  优惠券
 */
@SuppressLint("HandlerLeak") 
public class CouponActivity extends BackableTitleBarActivity implements OnLoadDataActionListener{
	@ViewInject(id = R.id.cupon_radio0,click = "butClick") RadioButton mRadio0;
	@ViewInject(id = R.id.cupon_radio1,click = "butClick") RadioButton mRadio1;
	@ViewInject(id = R.id.cupon_radio2,click = "butClick") RadioButton mRadio2;
	@ViewInject(id = R.id.coupon_loading_text) TextView mLoadingText;
	@ViewInject(id = R.id.coupon_empty_relat)RelativeLayout mEmptyRelat;
	@ViewInject(id = R.id.bt)  Button mButton;

	PullToRefreshListView mRefreshListView;
	RefreshViewLoadMoreProxy mLoadMoreProxy;
	private List<CouponCode> mCouponCodes;
	private int nowPage = 1;
	private CouponAdapter mAdapter;
	private String status = "unused";
	private BadgeView badge;
	private int total;
	private MyHandler mHandler;

	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.activity_coupon);
		FinalActivity.initInjectedView(this);
		getTitleBar().setTitle(R.string.mine_coupon);
		
		mHandler = new MyHandler(this);
		initBadge();
		
		getlist();
	}
	
	private void initBadge() {
		badge = new BadgeView(this, mButton);
		badge.setBadgeBackgroundColor(Color.WHITE);
		badge.setTextColor(getResources().getColor(R.color.holo_title));
	}
	
	private void updateBadge(int num) {
		if(num <= 0 ){
			if(badge.isShown()){
				badge.hide();
			}
		}else {
			badge.setText(num + "");
			if (!badge.isShown()) badge.show(true);
		}		

	}

	private void getlist() {

		mRefreshListView = (PullToRefreshListView) findViewById(R.id.coupon_list);
		mRefreshListView.setEmptyView(mEmptyRelat);
		mRefreshListView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));

		mAdapter = new CouponAdapter(this,R.layout.item_coupon_list);
		mRefreshListView.setAdapter(mAdapter);

		mLoadMoreProxy = new RefreshViewLoadMoreProxy(mRefreshListView, Mode.BOTH,0,0);
		mLoadMoreProxy.setOnLoadDataActionListener(this);
		mLoadMoreProxy.refreshing();

	}

	@Override
	public void onRefresh(int page) {
		updateCouponList(1, true);
	}
	@Override
	public void onLoadMore(int page) {
		nowPage++;
		updateCouponList(nowPage, false);
	}

	private void updateCouponList(final int pageNum,final boolean isRefresh){

		new Thread(){
			public void run() {
				try{
					WebClient client = WebClient.getInstance(CouponActivity.this);

					PageEntity<CouponCode> entry = client.getCouponList(status,pageNum, 20,"", "");
					int totlePage = entry.getTotalPages();
					if("unused".equals(status)){
						total = entry.getTotal();
						mHandler.sendEmptyMessage(2);
					}

					mCouponCodes = entry.getContent();
					if(pageNum > totlePage){
						App.showShortToast(R.string.the_end_page);
						mCouponCodes = null;
					}
				} catch (WebException e) {
					if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode()))
						mCouponCodes = null;
					else
						e.printStackTrace();
				}

				if(isRefresh)
					mHandler.sendEmptyMessage(0);	
				else
					mHandler.sendEmptyMessage(1);
			};
		}.start();

	}
	
	private class MyHandler extends Handler{
		
		private WeakReference<Activity> mActivity;
		
		private MyHandler(Activity activity){
			mActivity = new WeakReference<Activity>(activity);
		}
		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			if( mActivity.get() != null ){
				switch (msg.what) {
				case 0:
					canClick(true);
					mAdapter.update(mCouponCodes);
					mRefreshListView.onRefreshComplete();
					break;
				case 1:
					canClick(true);
					mAdapter.append(mCouponCodes);
					mRefreshListView.onRefreshComplete();
					break;
				case 2:
					updateBadge(total); 
					break;

				default:
					break;
				}
				
			}
		}
		
	} 


	public void butClick(View v){
		if (v == mRadio0 ){
			status = "unused";
			onRefresh(1);
			canClick(false);
		}
		if(v == mRadio1 ){
			status = "used";
			onRefresh(1);
			canClick(false);

		}
		if (v == mRadio2 ){
			status = "overdue";
			onRefresh(1);
			canClick(false);
		}
	}



	public class CouponAdapter extends AbsViewHolderAdapter<CouponCode>{

		public CouponAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}
		@Override
		protected void bindData(int pos, CouponCode itemData) {
			TextView mText1 = getViewFromHolder(R.id.item_coupon_text1);
			TextView mText2 = getViewFromHolder(R.id.item_coupon_text2);
			TextView mText3 = getViewFromHolder(R.id.item_coupon_number);
			TextView mText4 = getViewFromHolder(R.id.item_coupon_time_out);
			ImageView mImg = getViewFromHolder(R.id.coupon_status_img);
			
			String mCouponType = itemData.getCoupon().getCouponType().toString();
			if("fullgive".equals(mCouponType)){
				mText1.setText("赠");
			}else if("fullreduction".equals(mCouponType)){
				mText1.setText("￥"+itemData.getCoupon().getPreferentialAmount() );
			}else if("gift".equals(mCouponType)){
				mText1.setText("礼品");

			}else if("cash".equals(mCouponType)){
				mText1.setText("现金");
			}
			
			mText2.setText(itemData.getCoupon().getName());
			mText3.setText(itemData.getCouponCode());
			mText4.setText(DateTimeUtil.getDateTime1(itemData.getCoupon().getBeginDate())+"--"+DateTimeUtil.getDateTime1(itemData.getCoupon().getEndDate()));

//			if("used".equals(itemData.getStatus())){
//				mImg.setImageResource(R.drawable.coupon_used);
//			}else if ("overdue".equals(itemData.getStatus())) {
//				mImg.setImageResource(R.drawable.coupon_overdue);
//			}else if("unused".equals(itemData.getStatus())){
//				mImg.setImageResource(R.drawable.coupon_noused);
//			}
			
			if( itemData.isUsed()){
				mImg.setImageResource(R.drawable.coupon_used);
			}else {
				mImg.setImageResource(R.drawable.coupon_noused);
			}
			
		}

	}

	private void canClick(Boolean b){
		mRadio0.setClickable(b);
		mRadio1.setClickable(b);
		mRadio2.setClickable(b);

		if(b){
			mLoadingText.setVisibility(View.GONE);
		}else {
			mLoadingText.setVisibility(View.VISIBLE);
		}

	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacksAndMessages(null);
	}




}
